package com.leyou.item.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.common.dto.PageResult;
import com.leyou.common.exception.pojo.ExceptionEnum;
import com.leyou.common.exception.pojo.LyException;
import com.leyou.item.entity.Brand;
import com.leyou.item.mapper.BrandMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service
@Transactional
public class BrandService {

    @Autowired
    private BrandMapper brandMapper;

    public PageResult<Brand> brandPageQuery(String key, Integer page, Integer rows, String sortBy, Boolean desc) {
        //设置分页条件 跟在分页条件后的第一个mybatis查询会被分页
        PageHelper.startPage(page, rows);
        //提供通用mapper复杂条件查询对象Example
        Example example = new Example(Brand.class);
        //封装复杂查询对象之封装查询条件
        Example.Criteria criteria = example.createCriteria();
        //判断是否有查询条件
        if(!StringUtils.isEmpty(key)){
            criteria.orEqualTo("id", key);
            criteria.orLike("name", "%"+key+"%");
            criteria.orEqualTo("letter", key.toUpperCase());
        }
        //封装复杂查询对象之封装排序条件   select * from tb_brand where id=xx or name=xx order by name desc
        if(!StringUtils.isEmpty(sortBy)){
            example.setOrderByClause(sortBy+" "+(desc?"DESC":"ASC"));
        }
        //mybatis查询 其实这里已经分页了 brands已经是分页后的数据了
        List<Brand> brands = brandMapper.selectByExample(example);
        //得到pagehelper的分页对象
        PageInfo<Brand> pageInfo = new PageInfo<>(brands);
        //封装自定义的分页对象PageResult
        PageResult<Brand> pageResult = new PageResult<>(pageInfo.getTotal(),
                pageInfo.getPages(),
                pageInfo.getList());
        return pageResult;
    }

    public void saveBrand(Brand brand, List<Long> cids) {
        //保存品牌对象
        brandMapper.insertSelective(brand);
        //保存分类和品牌的中间表
        brandMapper.insertCategoryAndBrand(cids, brand.getId());
    }

    public Brand findBrandById(Long id) {
        Brand brand = brandMapper.selectByPrimaryKey(id);
        if(brand==null){
            throw new LyException(ExceptionEnum.BRAND_NOT_FOUND);
        }
        return brand;
    }

    public List<Brand> findBrandsByCid(Long cid) {
        List<Brand> list = brandMapper.findBrandsByCid(cid);
        if(CollectionUtils.isEmpty(list)){
            throw new LyException(ExceptionEnum.BRAND_NOT_FOUND);
        }
        return list;
    }

    public List<Brand> findBrandsByIds(List<Long> ids) {
        List<Brand> list = brandMapper.selectByIdList(ids);
        if(CollectionUtils.isEmpty(list)){
            throw new LyException(ExceptionEnum.BRAND_NOT_FOUND);
        }
        return list;
    }
}
